package com.smartcommunity.controller.log;

import com.alibaba.fastjson.JSONObject;
import com.smartcommunity.bean.constant.Constant;
import com.smartcommunity.bean.entity.User;
import com.smartcommunity.bean.enumeration.ResultCode;
import com.smartcommunity.bean.model.Result;
import com.smartcommunity.bean.model.UserAgent;
import com.smartcommunity.controller.BaseController;
import com.smartcommunity.log.interceptor.OperatorLogUtil;
import com.smartcommunity.log.model.OperateLogModel;
import com.smartcommunity.log.model.SearchLogModel;
import com.smartcommunity.log.service.LogSDK;
import com.smartcommunity.utils.ToolDateTime;
import com.smartcommunity.utils.UserAgentUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/log")
@Api(value = "日志管理", tags = "日志管理")
public class LogController extends BaseController {

    @Autowired
    private HttpServletRequest request;

    /**
     * 系统操作日志查询
     * @return
     */
    @PostMapping("/list")
    @ApiOperation(value = "系统操作日志查询", notes = "系统操作日志查询")
    public Result list(@RequestBody SearchLogModel searchLogModel){
        //获取当前登录用户，不是admin，只能查询自己的操作日志
        User user =getCurrentUser();
        if(user !=null && !user.isAdmin()){
            searchLogModel.setUserId(String.valueOf(user.getAccount()));
        }
        JSONObject jsonObject = LogSDK.query(searchLogModel);
        if(jsonObject.containsKey("code") &&  jsonObject.getInteger("code") == 200){
            return Result.ok(jsonObject.getJSONObject("data"));
        }
        return Result.error(ResultCode.ERROR);
    }

    @PostMapping("/save")
    @ApiOperation(value = "系统操作日志保存", notes = "系统操作日志保存")
    public Result save(@RequestBody OperateLogModel operateLogModel){
        // 客户端浏览器类型判断
        String userAgent = request.getHeader("User-Agent");
        UserAgent userAgentObj = UserAgentUtil.getUserAgent(userAgent);
        operateLogModel.setSystemCode(Constant.SYSTEMCODE);//系统代号
        operateLogModel.setRequestUrl(String.valueOf(request.getRequestURL()));//请求地址
        operateLogModel.setIp(OperatorLogUtil.getCliectIp(request));//请求IP地址
        operateLogModel.setUserAgent(userAgentObj != null ? userAgentObj.getPlatformAndBrowser() : "");//客户端代理
        operateLogModel.setCreateTime(ToolDateTime.getDateByTime());//操作时间
        operateLogModel.setOperateStatus(ResultCode.SUCCESS.getMsg());//操作状态
        LogSDK.saveLog(operateLogModel);
        return Result.ok();
    }

}
